package ro.pub.cs.hwchecker.comm.client.json;

import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONValue;

import ro.pub.cs.hwchecker.comm.client.data.LoginCredentials;
import ro.pub.cs.hwchecker.comm.client.req.CheckerCallback;
import ro.pub.cs.hwchecker.comm.client.req.CheckerRequest;
import ro.pub.cs.hwchecker.comm.client.req.CheckerRequestException;
import ro.pub.cs.hwchecker.comm.client.req.LoginRequestBuilder;


public class JSONLoginRequestBuilder extends JSONRequestBuilder implements LoginRequestBuilder{
	private static final String authURL = "auth";
	
	private String convertCredentials(LoginCredentials c) {
		return buildQueryString(
				new String[] { "username", "password" }, 
				new String[] { c.username, c.password });
	}

	public CheckerRequest performLogin(LoginCredentials c,
			final CheckerCallback<Void> callback) throws CheckerRequestException {
		
		// Prepare the data to send
		String postData = convertCredentials(c); 
		

		CheckerRequest req = performRequest(GWT.getHostPageBaseURL() + authURL, postData, new CheckerCallback<JSONValue>() {

			public void onCheckerError(CheckerRequest req,
					CheckerRequestException error) {
				// Propagate the error
				callback.onCheckerError(req, error);
			}

			public void onCheckerResponse(CheckerRequest req, JSONValue response) {
				callback.onCheckerResponse(req, null);
			}
		});

		return req;
	}

}
